<template>
  <div class="product-detail-test-container">
    <h2>产品明细新增功能测试</h2>
    
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <span>产品明细新增API测试</span>
        </div>
      </template>
      
      <div class="test-form">
        <el-form :model="testForm" label-width="120px" :rules="formRules" ref="formRef">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入库单号" prop="entryOrderNumber">
                <el-input v-model="testForm.entryOrderNumber" placeholder="请输入入库单号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品ID" prop="productId">
                <el-input-number v-model="testForm.productId" :min="1" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="产品名称" prop="productName">
                <el-input v-model="testForm.productName" placeholder="请输入产品名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品编号" prop="productNumber">
                <el-input v-model="testForm.productNumber" placeholder="请输入产品编号" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="产品规格" prop="productSpecification">
                <el-input v-model="testForm.productSpecification" placeholder="请输入产品规格" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="库存单位" prop="inventoryUnit">
                <el-input v-model="testForm.inventoryUnit" placeholder="请输入库存单位" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入库数量" prop="inventoryQuantity">
                <el-input-number v-model="testForm.inventoryQuantity" :min="1" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="当前库存" prop="current">
                <el-input-number v-model="testForm.current" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="最大库存" prop="maxInventory">
                <el-input-number v-model="testForm.maxInventory" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最小库存" prop="minInventory">
                <el-input-number v-model="testForm.minInventory" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="安全库存" prop="safetyInventory">
                <el-input-number v-model="testForm.safetyInventory" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        
        <div class="test-buttons">
          <el-button type="primary" @click="testAddProductDetail" :loading="loading">
            测试新增产品明细
          </el-button>
          <el-button type="success" @click="testUpdateProductDetail" :loading="updateLoading">
            测试更新产品明细
          </el-button>
          <el-button type="warning" @click="testGetProductDetails" :loading="getLoading">
            测试获取产品明细
          </el-button>
          <el-button @click="resetForm">
            重置表单
          </el-button>
        </div>
      </div>
      
      <div class="test-results">
        <h3>测试结果：</h3>
        <el-input
          v-model="testResult"
          type="textarea"
          :rows="15"
          placeholder="测试结果将显示在这里..."
          readonly
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { MES_LXK_ApiHost } from '@/utils/Interceptors'

const formRef = ref<FormInstance>()
const testResult = ref('')
const loading = ref(false)
const updateLoading = ref(false)
const getLoading = ref(false)

// 测试表单数据
const testForm = reactive({
  entryOrderNumber: `TEST${Date.now()}`,
  productId: 1,
  productName: '测试产品',
  productNumber: 'P000001',
  productSpecification: '测试规格',
  inventoryUnit: '个',
  inventoryQuantity: 10,
  current: 100,
  maxInventory: 1000,
  minInventory: 100,
  safetyInventory: 200,
  productAttribute: '',
  processRoute: '',
  isDelete: false,
  createdBy: 'test',
  modifiedBy: 'test'
})

// 表单验证规则
const formRules: FormRules = {
  entryOrderNumber: [
    { required: true, message: '请输入入库单号', trigger: 'blur' }
  ],
  productId: [
    { required: true, message: '请输入产品ID', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '请输入产品名称', trigger: 'blur' }
  ],
  productNumber: [
    { required: true, message: '请输入产品编号', trigger: 'blur' }
  ],
  inventoryQuantity: [
    { required: true, message: '请输入入库数量', trigger: 'blur' }
  ]
}

const logResult = (title: string, result: any) => {
  const timestamp = new Date().toLocaleString()
  const resultStr = JSON.stringify(result, null, 2)
  testResult.value = `[${timestamp}] ${title}:\n${resultStr}\n\n${testResult.value}`
}

// 测试新增产品明细
const testAddProductDetail = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const payload = {
      entryOrderNumber: testForm.entryOrderNumber,
      EntryOrderNumber: testForm.entryOrderNumber,
      productId: testForm.productId,
      productName: testForm.productName,
      productNumber: testForm.productNumber,
      productSpecification: testForm.productSpecification,
      inventoryUnit: testForm.inventoryUnit,
      productAttribute: testForm.productAttribute,
      processRoute: testForm.processRoute,
      maxInventory: testForm.maxInventory,
      minInventory: testForm.minInventory,
      safetyInventory: testForm.safetyInventory,
      current: testForm.current,
      inventoryQuantity: testForm.inventoryQuantity,
      num: testForm.inventoryQuantity,
      isDelete: testForm.isDelete,
      createdBy: testForm.createdBy,
      modifiedBy: testForm.modifiedBy,
      createdTime: new Date().toISOString(),
      modifiedTime: new Date().toISOString()
    }
    
    logResult('发送的请求数据', payload)
    
    // 尝试不同的API端点
    let response
    let endpoint = ''
    
    try {
      endpoint = '/api/ProductDetail/Add'
      response = await MES_LXK_ApiHost.post(endpoint, payload)
      logResult(`API调用成功 (${endpoint})`, response.data)
      ElMessage.success('产品明细新增测试成功')
    } catch (error: any) {
      logResult(`API调用失败 (${endpoint})`, {
        error: error.message,
        response: error.response?.data,
        status: error.response?.status
      })
      
      try {
        endpoint = '/api/ProductDetail/AddProductDetail'
        response = await MES_LXK_ApiHost.post(endpoint, payload)
        logResult(`API调用成功 (${endpoint})`, response.data)
        ElMessage.success('产品明细新增测试成功')
      } catch (error2: any) {
        logResult(`API调用失败 (${endpoint})`, {
          error: error2.message,
          response: error2.response?.data,
          status: error2.response?.status
        })
        
        try {
          endpoint = '/api/InboundOrderDetail/Add'
          response = await MES_LXK_ApiHost.post(endpoint, payload)
          logResult(`API调用成功 (${endpoint})`, response.data)
          ElMessage.success('产品明细新增测试成功')
        } catch (error3: any) {
          logResult(`API调用失败 (${endpoint})`, {
            error: error3.message,
            response: error3.response?.data,
            status: error3.response?.status
          })
          ElMessage.error('所有API端点都调用失败')
        }
      }
    }
  } catch (error: any) {
    logResult('表单验证失败', error)
    ElMessage.error('表单验证失败')
  } finally {
    loading.value = false
  }
}

// 测试更新产品明细
const testUpdateProductDetail = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    updateLoading.value = true
    
    const payload = {
      id: 1, // 需要提供要更新的记录ID
      entryOrderNumber: testForm.entryOrderNumber,
      EntryOrderNumber: testForm.entryOrderNumber,
      productId: testForm.productId,
      productName: testForm.productName,
      productNumber: testForm.productNumber,
      productSpecification: testForm.productSpecification,
      inventoryUnit: testForm.inventoryUnit,
      productAttribute: testForm.productAttribute,
      processRoute: testForm.processRoute,
      maxInventory: testForm.maxInventory,
      minInventory: testForm.minInventory,
      safetyInventory: testForm.safetyInventory,
      current: testForm.current,
      inventoryQuantity: testForm.inventoryQuantity,
      num: testForm.inventoryQuantity,
      isDelete: testForm.isDelete,
      createdBy: testForm.createdBy,
      modifiedBy: testForm.modifiedBy,
      createdTime: new Date().toISOString(),
      modifiedTime: new Date().toISOString()
    }
    
    logResult('发送的更新请求数据', payload)
    
    // 尝试不同的API端点
    let response
    let endpoint = ''
    
    try {
      endpoint = '/api/ProductDetail/Update'
      response = await MES_LXK_ApiHost.put(endpoint, payload)
      logResult(`更新API调用成功 (${endpoint})`, response.data)
      ElMessage.success('产品明细更新测试成功')
    } catch (error: any) {
      logResult(`更新API调用失败 (${endpoint})`, {
        error: error.message,
        response: error.response?.data,
        status: error.response?.status
      })
      
      try {
        endpoint = '/api/InboundOrderDetail/Update'
        response = await MES_LXK_ApiHost.put(endpoint, payload)
        logResult(`更新API调用成功 (${endpoint})`, response.data)
        ElMessage.success('产品明细更新测试成功')
      } catch (error2: any) {
        logResult(`更新API调用失败 (${endpoint})`, {
          error: error2.message,
          response: error2.response?.data,
          status: error2.response?.status
        })
        ElMessage.error('所有更新API端点都调用失败')
      }
    }
  } catch (error: any) {
    logResult('表单验证失败', error)
    ElMessage.error('表单验证失败')
  } finally {
    updateLoading.value = false
  }
}

// 测试获取产品明细
const testGetProductDetails = async () => {
  getLoading.value = true
  try {
    const orderNumber = testForm.entryOrderNumber || 'TEST123'
    logResult('测试获取产品明细，入库单号', orderNumber)
    
    // 尝试不同的API端点
    const possiblePaths = [
      `/api/ProductDetail/GetByOrderNumber/${orderNumber}`,
      `/api/ProductDetail/GetDetails/${orderNumber}`,
      `/api/InboundOrder/GetProductDetails/${orderNumber}`,
      `/api/ProductDetail?entryOrderNumber=${orderNumber}`,
      `/api/InboundOrderDetail?entryOrderNumber=${orderNumber}`
    ]
    
    let lastError = null
    
    for (const path of possiblePaths) {
      try {
        logResult(`尝试API路径`, path)
        const response = await MES_LXK_ApiHost.get(path)
        logResult(`获取明细成功 (${path})`, response.data)
        ElMessage.success('获取产品明细测试成功')
        return
      } catch (error: any) {
        logResult(`API路径失败 (${path})`, {
          error: error.message,
          response: error.response?.data,
          status: error.response?.status
        })
        lastError = error
        continue
      }
    }
    
    logResult('所有API路径都失败', lastError)
    ElMessage.error('所有获取明细API端点都调用失败')
  } catch (error: any) {
    logResult('获取明细测试失败', error)
    ElMessage.error('获取明细测试失败')
  } finally {
    getLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  testForm.entryOrderNumber = `TEST${Date.now()}`
  testResult.value = ''
}
</script>

<style scoped>
.product-detail-test-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.test-form {
  margin-bottom: 20px;
}

.test-buttons {
  display: flex;
  gap: 12px;
  margin-top: 20px;
}

.test-results {
  margin-top: 20px;
}

.test-results h3 {
  margin-bottom: 12px;
  color: #303133;
}
</style>
